//
//  BabyProfileView.m
//  BabyHelper
//
//  Created by  thomas on 11-2-13.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "BabyProfileView.h"
#import "QWeiboSyncApi.h"
#import "QWeiboAsyncApi.h"
#import "Connections.h"
#import "QVerifyWebViewController.h"
#import "BabyHelperAppDelegate.h"
#import "ComposeViewController.h"

@implementation BabyProfileView
@synthesize connection;
@synthesize responseData;
@synthesize processingLabel;

- (void)viewDidLoad {
	self.title = NSLocalizedString(@"Settings", @"");
    [super viewDidLoad];
	//set background image
	self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background"]];
	self.view.backgroundColor = [UIColor clearColor];
	//set navigation background color
	self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:navBarRed green:navBarGreen blue:navBarBlue alpha:navBarAlpha];
	
	int kScreenWidth = 320;
	int kScreenHeight = 480;
	self.processingLabel = [[TTActivityLabel alloc] initWithStyle:TTActivityLabelStyleBlackBezel];
	self.processingLabel.text = NSLocalizedString(@"Backing up, don't exit",@"");
	//label.progress = 0.1;
	[self.processingLabel sizeToFit];
	//label.frame = CGRectMake(0, lastView.bottom+10, self.view.width, label.height);
	[self.processingLabel setCenter:CGPointMake(kScreenWidth/2.0, kScreenHeight/2.0-40)]; // I do this because I'm in landscape mode
	[self.view addSubview:self.processingLabel];
	self.processingLabel.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	[self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	int numberOfRows = 0;
	switch(section){
		case 0:
			numberOfRows = 3;
			break;
		case 1:
			numberOfRows = 3;
			break;
		case 2:
			numberOfRows = 2;
			break;
		default:
			break;
	}
	return numberOfRows;
}

/*
- (NSString *)tableView:(UITableView *)tv titleForHeaderInSection:(NSInteger)section
{
	NSString *title = nil;
	
	switch(section){
		case 0:
			title = NSLocalizedString(@"Basic Settings", @"");
			break;
		case 1:
			title = NSLocalizedString(@"Account", @"");
			break;
		case 2:
			title = NSLocalizedString(@"Help", @"");
			break;
		default:
			break;
	}
	return title;
}
 */

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

	Dao *dao = [Dao getInstance];
	BabyProfile *babyProfile = [[BabyProfile alloc]init];
	[dao LoadBabyProfile:babyProfile];
	
	if (indexPath.section == 0 ) {
		switch (indexPath.row) {
			case 0:
				cell.imageView.image = [UIImage imageNamed:@"ID"];
				cell.textLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Name: %@", @""),babyProfile.Name];
				cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
				break;
			case 1:
				cell.imageView.image = [UIImage imageNamed:@"birthday"];
				cell.textLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Birthday: %@", @""),babyProfile.BirthdayStr];
				cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;				
				break;
			case 2:
				cell.imageView.image = [UIImage imageNamed:@"gender"];
				if( babyProfile.Gender == BabyGenderFemale )
					cell.textLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Gender: %@", @""),NSLocalizedString(@"Girl", @"")];
				else 
					cell.textLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Gender: %@", @""),NSLocalizedString(@"Boy", @"")];
				cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
				break;				
			default:
				cell.imageView.image = nil;				
				break;
		}		
	}
	[babyProfile release];
	
	if (indexPath.section == 1 ) {
		switch (indexPath.row) {
			case 0:
				cell.imageView.image = [UIImage imageNamed:@"sina"];
				cell.textLabel.text = NSLocalizedString(@"Sina Weibo Bind", @"");
				
				BabyHelperAppDelegate *appDelegate = (BabyHelperAppDelegate *)[[UIApplication sharedApplication] delegate];
				UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: appDelegate._engine delegate: self];
				if (controller) 
				{
					cell.accessoryView = nil;
				}else {
					UIImage *buttonUpImage = [UIImage imageNamed:@"button_up"];
					UIImage *buttonDownImage = [UIImage imageNamed:@"button_down"];
					UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
					button.frame = CGRectMake(0.0, 0.0, buttonUpImage.size.width-5, buttonUpImage.size.height-5);
					[button setBackgroundImage:buttonUpImage forState:UIControlStateNormal];
					[button setBackgroundImage:buttonDownImage forState:UIControlStateHighlighted];
					button.titleLabel.font = [UIFont systemFontOfSize:14];
					[button setTitle:NSLocalizedString(@"log off", @"") forState:UIControlStateNormal];
					[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
					cell.accessoryView = button;
				}	
				break;
			case 1:
				cell.imageView.image = nil;
				cell.textLabel.text = NSLocalizedString(@"Share activity record", @"");
				cell.selectionStyle = UITableViewCellSelectionStyleNone;
				UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];
				cell.accessoryView = switchView;
				
				NSString *result = [[NSUserDefaults standardUserDefaults] stringForKey:@"BIND_WEIBO_WITH_SINGLE_ACTIVITY"];
				if(result == nil || [result isEqualToString:@"YES"] )
					[switchView setOn:YES animated:NO];
				else 
					[switchView setOn:NO animated:NO];
				
				[switchView addTarget:self action:@selector(weiboWithBabyActivityEntryChanged:) forControlEvents:UIControlEventValueChanged];
				[switchView release];
				break;									
			case 2:
				cell.imageView.image = [UIImage imageNamed:@"email"];
				cell.textLabel.text = NSLocalizedString(@"Email all records", @"");
				break;				
			case 3:
				cell.imageView.image = [UIImage imageNamed:@"cloud"];
				cell.textLabel.text = NSLocalizedString(@"Backup to server", @"");
				break;				
			default:
				cell.imageView.image = nil;				
				break;
		}		
	}
		
	if (indexPath.section == 2 ) {
		switch (indexPath.row) {
			case 0:
				cell.textLabel.text = NSLocalizedString(@"About", @"");
				cell.imageView.image = nil;				
				//cell.imageView.image = [UIImage imageNamed:@"about"];
				cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
				break;
			case 1:
				cell.textLabel.text = NSLocalizedString(@"Feedback", @"");
				cell.imageView.image = nil;
				break;
			default:
				cell.imageView.image = nil;
				break;
		}		
	}
	
	
	cell.backgroundColor = [UIColor colorWithRed:cellBackgroundSettingRed green:cellBackgroundSettingGreen 
											blue:cellBackgroundSettingBlue alpha:cellBackgroundSettingAlpha];
    return cell;
}

- (void)weiboWithBabyActivityEntryChanged:(id)sender{
    UISwitch* switchControl = sender;
	
	if(switchControl.on)
		[[NSUserDefaults standardUserDefaults] setValue:@"YES"  forKey:@"BIND_WEIBO_WITH_SINGLE_ACTIVITY"];
	else
		[[NSUserDefaults standardUserDefaults] setValue:@"NO" forKey:@"BIND_WEIBO_WITH_SINGLE_ACTIVITY"];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
	if(indexPath.section == 0){
		switch (indexPath.row) {
			case 0:
			{
				BabyNameView *childView = [[BabyNameView alloc] initWithNibName:@"BabyNameView" bundle:nil];
				[self.navigationController pushViewController:childView animated:YES];
				[childView release];			
				break;
			}
			case 1:
			{
				BabyBirthdayView *childView = [[BabyBirthdayView alloc] initWithNibName:@"BabyBirthdayView" bundle:nil];
				[self.navigationController pushViewController:childView animated:YES];
				[childView release];			
				break;
			}
			case 2:
			{
				BabyGenderView *childView = [[BabyGenderView alloc] initWithNibName:@"BabyGenderView" bundle:nil];
				[self.navigationController pushViewController:childView animated:YES];
				[childView release];			
				break;
			}
			default:
				break;
		}
	}
	
	if (indexPath.section == 1) {
		switch (indexPath.row) {
			case 0:
			{
				BabyHelperAppDelegate *appDelegate = 
				(BabyHelperAppDelegate *)[[UIApplication sharedApplication] delegate];
				[appDelegate._engine signOut];
				
				UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: appDelegate._engine delegate: self];
				
				if (controller) 
					[self presentModalViewController: controller animated: YES];
				else 
				{
					UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"") 
																	message:NSLocalizedString(@"Log successfully, you can send twitter directly!", @"")
																   delegate:nil 
														  cancelButtonTitle:@"OK"
														  otherButtonTitles:nil];
					[alert show];
					[alert release];					
				}
				break;
			}
			case 1:
			{
				break;
			}
			case 2:
			{
				Dao *dao = [Dao getInstance];
				int totalCount = [dao GetCountUnderCondition:@"ID" condition:@""];
				if (totalCount == 0) {
					UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"") 
																	message:NSLocalizedString(@"No record in database!", @"")
																   delegate:nil 
														  cancelButtonTitle:@"OK"
														  otherButtonTitles:nil];
					[alert show];
					[alert release];
				}else {
					[self SendMail];
				}
				break;				
			}
			case 3:
			{
				Dao *dao = [Dao getInstance];
				RequestCommand *command = [[RequestCommand alloc]init];
				UserProfile *userProfile = [[UserProfile alloc]init];
				BabyProfile *babyProfile = [[BabyProfile alloc]init];
				[dao LoadBabyProfile:babyProfile];
				command.protocolVersion = 1;
				command.requestType     = 1;
				userProfile.type = @"Sina";
				userProfile.userid = @"aaaaaaa";
				userProfile.username = @"ibabynotes@sina.com";
				userProfile.app_token = SINA_APP_KEY;
				userProfile.app_secret = SINA_APP_SECRET;
				userProfile.access_token = @"xxxx";
				userProfile.web_password = @"null";
				userProfile.web_username = @"null";
				userProfile.email = @"null";
				userProfile.usertype = @"iphone";
				userProfile.babyname = babyProfile.Name;
				userProfile.birthday = babyProfile.BirthdayStr;
			    userProfile.gender   = [NSString stringWithFormat:@"%d",babyProfile.Gender];
				command.userProfile = userProfile;			
				[dao LoadBabyProfile:babyProfile];
				self.processingLabel.text = @"正在备份数据....";
				self.processingLabel.hidden = NO;
				command.babyGrowEntries = [[NSMutableArray alloc]init];
				command.babyActivityEntries = [[NSMutableArray alloc]init];				
				[dao QueryBabyActivityWith:@"ORDER BY TIMESTAMP DESC" records:command.babyActivityEntries];
				[dao QueryBabyGrowEntryWith:@"ORDER BY BabyGrowTable.TIMESTAMP DESC" records:command.babyGrowEntries];
				NSString *json = [command JSONRepresentation];
				NSLog(@"%@",json);
				
				@try {
					ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://ibabycare.gotoip55.com/getpost.php"]];
					[request addRequestHeader:@"User-Agent" value:@"ASIHTTPRequest"];
					[request setPostValue:json forKey:@"Request"];
					[request setTimeOutSeconds:20];
					[request setDelegate:self];
					[request startAsynchronous];
					self.processingLabel.text = NSLocalizedString(@"Backing up, don't exit",@"");
					self.processingLabel.hidden = NO;
				}
				@catch (NSException * e) {
					NSLog(@"create thumbnail exception.");
					self.processingLabel.hidden = YES;
				}
				@finally {
					//do nothing
				}				
			}
			default:
				break;
		}
	}
	
	if (indexPath.section == 2) {
		switch (indexPath.row) {
			case 0:
			{				
				AboutView *childView = [[AboutView alloc] initWithNibName:@"AboutView" bundle:nil];
				[self.navigationController pushViewController:childView animated:YES];
				[childView release];			
				break;
			}
			case 1:
			{
				BabyHelperAppDelegate *appDelegate = (BabyHelperAppDelegate *)[[UIApplication sharedApplication] delegate];
				UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: appDelegate._engine delegate: self];
				if (controller) 
				{
					UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"") 
																	message:NSLocalizedString(@"You are not log in yet", @"")
																   delegate:nil 
														  cancelButtonTitle:@"OK"
														  otherButtonTitles:nil];
					[alert show];
					[alert release];
				}
				else {
					[OAuthEngine setCurrentOAuthEngine:appDelegate._engine];
					ComposeViewController *composeViewController = [[ComposeViewController alloc]init];
					[self presentModalViewController:composeViewController animated:YES];
					composeViewController.messageTextField.text = FEEDBACK_TEMPLATE;
					[composeViewController newTweet];					
				}
				break;
			}

			default:
				break;
		}
	}
	
}

- (void)dealloc {
    [super dealloc];
}

- (void)SendMail{
	Dao *dao = [Dao getInstance];
	[dao SaveAllBabyEntriesToFile];
	
	NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
	NSString *pathHome = [path objectAtIndex:0];
	NSString *babyReportFilePath = [pathHome stringByAppendingPathComponent:@"/iBabyNotes_Report.txt"];
	
	if( [MFMailComposeViewController canSendMail] )
	{
		MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
		picker.mailComposeDelegate = self;
		
		NSUserDefaults *prefs   = [NSUserDefaults standardUserDefaults];

		[picker setSubject:[NSString stringWithFormat:@"%@%@",[prefs stringForKey:@"Name"],NSLocalizedString(@"iBabyNotes", @"")]];
	
		NSLog(@"filePath = %@",babyReportFilePath);
		
		NSData* activityData = [NSData dataWithContentsOfFile:babyReportFilePath]; 
		[picker addAttachmentData:activityData mimeType:@"html" fileName:@"iBabyNotes_Report.html"];
		
		NSString *emailBody = NSLocalizedString(@"Welcome use iBabyNotes", @"");
		[picker setMessageBody:emailBody isHTML:YES];
		
		[self presentModalViewController:picker animated:YES];
		[picker release];
	}
}

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {

	NSString *message;
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MFMailComposeResultCancelled:
			message = NSLocalizedString(@"Mail cancelled", @"");
			break;
		case MFMailComposeResultSaved:
			message = NSLocalizedString(@"Mail saved", @"");
			break;
		case MFMailComposeResultSent:
			message = NSLocalizedString(@"Send successful", @"");
			break;
		case MFMailComposeResultFailed:
			message = NSLocalizedString(@"Send Failed", @"");
			break;
		default:
			message = NSLocalizedString(@"Not send", @"");
			break;
	}
	
	if( result == MFMailComposeResultSent || result == MFMailComposeResultFailed )
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"") 
													message:message
												   delegate:nil 
										  cancelButtonTitle:@"OK"
										  otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
	[self dismissModalViewControllerAnimated:YES];
}

-(void)requestFinished:(ASIHTTPRequest *)request
{
	self.processingLabel.hidden = true;
	// 当以文本形式读取返回内容时用这个方法
	NSString *responseString = [request responseString];
	// 当以二进制形式读取返回内容时用这个方法
	//NSData *responseData = [request responseData];

	
	//NSString *responseString = @"{\"ProtocolVersion\":1,\"ResponseType\":\"1\",\"ErrorCode\":\"1\",\"ErrorDetails\":\"用户名密码错误\"}";
	NSLog(@"%@",responseString);
	
	NSLog(@"Receive the response %@",responseString);
	NSDictionary *response    = [responseString JSONValue];
	NSString *protocolVersion = [response objectForKey:@"ProtocolVersion"];
	NSString *responseType    = [response objectForKey:@"ResponseType"];
	NSString *errorCode       = [response objectForKey:@"ErrorCode"];	
	NSString *errorDetails    = [response objectForKey:@"ErrorDetails"];

	
	NSString *resultString;
    if (protocolVersion == nil) {
		resultString = @"Unexpected Result";
	}	
	
	else {
		resultString = [NSString stringWithFormat:@"ProtocolVersion:%@ ResponseType:%@ ErrorCode:%@ ErrorDetails: %@",
						protocolVersion,
						responseType,
						errorCode,
						errorDetails];
	}

	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"") 
													message:resultString
												   delegate:nil 
										  cancelButtonTitle:@"OK"
										  otherButtonTitles:nil];
	[alert show];
	[alert release];
	

}
- (void)requestFailed:(ASIHTTPRequest *)request
{
	self.processingLabel.hidden = true;
	NSError *error = [request error];
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"") 
													message:error.domain
												   delegate:nil 
										  cancelButtonTitle:@"OK"
										  otherButtonTitles:nil];
	[alert show];
	[alert release];
}

#pragma mark -
#pragma mark NSURLConnection delegate

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	
	self.responseData = [NSMutableData data];
	NSLog(@"total = %d", [response expectedContentLength]);
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
	
	BabyHelperAppDelegate *appDelegate = 
	(BabyHelperAppDelegate *)[[UIApplication sharedApplication] delegate];
	
	appDelegate.response = [[[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding] autorelease];
	
	self.connection = nil;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	
	BabyHelperAppDelegate *appDelegate = 
	(BabyHelperAppDelegate *)[[UIApplication sharedApplication] delegate];
	
	appDelegate.response = [NSString stringWithFormat:@"connection error:%@", error];
		
	//[QLoadingView hideWithAnimated:YES];
	self.connection = nil;
}

//function for WeiBo Auth Result
- (void) OAuthController: (OAuthController *) controller authenticatedWithUsername: (NSString *) username{
    [[controller.engine requestToken] storeInUserDefaultsWithServiceProviderName:@"SINA" prefix:@"REQUEST_TOKEN"];   
	[[controller.engine accessToken] storeInUserDefaultsWithServiceProviderName:@"SINA" prefix:@"ACCESS_TOKEN"];
	
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert",@"") 
													message:NSLocalizedString(@"Log in successfully", @"")
												   delegate:nil 
										  cancelButtonTitle:@"OK"
										  otherButtonTitles:nil];
	[alert show];
	[alert release];
}
- (void) OAuthControllerFailed: (OAuthController *) controller{
}
- (void) OAuthControllerCanceled: (OAuthController *) controller{
}

- (IBAction)buttonTapped:(id)sender
{
	UIAlertView *alert = [[UIAlertView alloc] init];
	[alert setTitle:NSLocalizedString(@"Alert",@"")];
	[alert setMessage:NSLocalizedString(@"Please confirm to log off", @"")];
	[alert setDelegate:self];
	[alert addButtonWithTitle:@"Yes"];
	[alert addButtonWithTitle:@"No"];
	[alert show];
	[alert release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == 0)
	{
		BabyHelperAppDelegate *appDelegate = (BabyHelperAppDelegate *)[[UIApplication sharedApplication] delegate];
		[appDelegate._engine signOut];
		[self.tableView reloadData];
	}
	else if (buttonIndex == 1)
	{
		// No
	}
}


//=============================================================================================================================
#pragma mark OAuthEngineDelegate
- (void) storeCachedOAuthData: (NSString *) data forUsername: (NSString *) username {
	NSUserDefaults			*defaults = [NSUserDefaults standardUserDefaults];
	
	[defaults setObject: data forKey: @"authData"];
	[defaults synchronize];
}

- (NSString *) cachedOAuthDataForUsername: (NSString *) username {
	return [[NSUserDefaults standardUserDefaults] objectForKey: @"authData"];
}

- (void)removeCachedOAuthDataForUsername:(NSString *) username{
	NSUserDefaults			*defaults = [NSUserDefaults standardUserDefaults];
	
	[defaults removeObjectForKey: @"authData"];
	[defaults synchronize];
}
@end
/*

 - (void)setBackgroundImageWithName:(NSString *)imageName
 {
 int kBackgroundViewTag = 1024768;
 
 self.view.backgroundColor = [UIColor clearColor];
 
 // create view
 UIImageView* bgview = [[UIImageView alloc] initWithFrame:self.view.bounds];
 
 // set view tag
 bgview.tag = kBackgroundViewTag;
 
 // set image
 [bgview setImage:[UIImage imageNamed:imageName]];    
 
 // remove old bgview if it exists
 UIView* oldView = [self.view viewWithTag:kBackgroundViewTag];
 [oldView removeFromSuperview];
 
 // add to super view
 [self.view addSubview:bgview];
 
 // release the bgview
 [bgview release];
 }
 
 - (void)setBackgroundImage:(UIImage *)image
 {
 int kBackgroundViewTag = 1024768;
 
 self.view.backgroundColor = [UIColor clearColor];
 
 // create view
 UIImageView* bgview = [[UIImageView alloc] initWithFrame:self.view.bounds];
 
 // set view tag
 bgview.tag = kBackgroundViewTag;
 
 // set image
 [bgview setImage:image];    
 
 // remove old bgview if it exists
 UIView* oldView = [self.view viewWithTag:kBackgroundViewTag];
 [oldView removeFromSuperview];
 
 // add to super view
 [self.view addSubview:bgview];
 
 // release the bgview
 [bgview release];
 }*/

/*				
 if (appDelegate.bindStatus && [appDelegate.bindStatus isEqualToString:@"OK"] &&
 appDelegate.tokenKey && ![appDelegate.tokenKey isEqualToString:@""] && 
 appDelegate.tokenSecret && ![appDelegate.tokenSecret isEqualToString:@""]) 
 {
 //Send Asyn
 QWeiboAsyncApi *api = [[[QWeiboAsyncApi alloc] init] autorelease];
 NSString *content = @"Hello world from my app again test";
 self.connection = [api publishMsgWithConsumerKey:appDelegate.appKey 
 consumerSecret:appDelegate.appSecret 
 accessTokenKey:appDelegate.tokenKey 
 accessTokenSecret:appDelegate.tokenSecret 
 content:content 
 imageFile:nil 
 resultType:RESULTTYPE_JSON
 delegate:self];
 
 //Send Sync
 QWeiboSyncApi *api = [[[QWeiboSyncApi alloc] init] autorelease];
 NSString *content = @"Hello world from my app again...";
 NSString *tmp = [api publishMsgWithConsumerKey:appDelegate.appKey 
 consumerSecret:appDelegate.appSecret 
 accessTokenKey:appDelegate.tokenKey 
 accessTokenSecret:appDelegate.tokenSecret 
 content:content 
 imageFile:nil 
 resultType:RESULTTYPE_JSON];
 NSLog(tmp);
 
 break;
 }
 else {					
 QWeiboSyncApi *api = [[[QWeiboSyncApi alloc] init] autorelease];
 
 NSString *retString;
 
 if ([appDelegate.bindName isEqualToString:@"SINA"] ) {
 retString = [api getRequestTokenWithConsumerKey:SINA_APP_KEY consumerSecret:SINA_APP_SECRET url:SINA_REQUEST_TOKEN_URL callbackUrl:SINA_BASE_URL];
 }
 if ([appDelegate.bindName isEqualToString:@"QQ"] ) {
 retString = [api getRequestTokenWithConsumerKey:TECENT_APP_KEY consumerSecret:TECENT_APP_SECRET url:QQ_REQUEST_TOKEN_URL callbackUrl:QQ_BASE_URL];
 }
 
 NSLog(@"Get requestToken:%@", retString);
 
 [appDelegate parseTokenKeyWithResponse:retString];
 
 QVerifyWebViewController *verifyController = [[QVerifyWebViewController alloc] init];
 
 [self.navigationController pushViewController:verifyController animated:YES];
 [verifyController release];
 break;
 }
 */

